package com.dllo.lanou.cookapp.volly;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.dllo.lanou.cookapp.BaseApplication;

import java.io.StringReader;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by xijinhua on 2016/2/13.
 */
public class VolleySingleton {

    private static VolleySingleton instanceSingleton;
    private RequestQueue queue;
    private ImageLoader imageLoader;
    private VolleySingleton(){
        queue = getQueue();
      imageLoader = new ImageLoader(queue,new MemoryCache());
    }

    public static VolleySingleton getInstance()  {
        if(instanceSingleton == null){
            synchronized ((VolleySingleton.class)){
                if (instanceSingleton == null){
                    instanceSingleton = new VolleySingleton();
                }
            }
        }
        return instanceSingleton;
    }

    private RequestQueue getQueue(){
        if (instanceSingleton == null){
            queue = Volley.newRequestQueue(BaseApplication.getContext());
        }
        return queue;
    }

    private static final  String TAG = "VolleySingleton";
    public <T> void addRequest(Request<T> request){
        request.setTag(TAG);
        queue.add(request);
    }
    public void addStringRequest(String url , Response.Listener listener,
                                 Response.ErrorListener errorListener){
        StringRequest request = new StringRequest(url,listener,errorListener);
        addRequest(request);
    }

    public ImageLoader getImageLoader(){
        return  imageLoader;
    }
    public Map<String, String> getHeaders() throws AuthFailureError {
        Map<String, String> map = new HashMap<String, String>();
        map.put("apikey", "4ee0087cd4103e3acbab0f8efbf0bbd1");
        return map;
    }
}
